package com.study.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author 陈烨庆
 * @date 2023/4/27
 */
@Controller
@RequestMapping("/myController")
public class MyController {


    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/userLogin")
    public String userLogin(String name, String pwd,
                            @RequestParam(defaultValue = "false") boolean rememberMe,
                            HttpSession session) {
        // 1. 获取 Subject 对象
        Subject subject = SecurityUtils.getSubject();
        // 2. 封装请求数据到 token
        AuthenticationToken token = new UsernamePasswordToken(name, pwd, rememberMe);
        // 3. 调用 login() 进行登录
        try {
            subject.login(token);

            // 放入数据
            session.setAttribute("user", token.getPrincipal().toString());
            // 跳转到main页面
            return "main";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登陆失败");
            return "登录失败";
        }
    }

    @GetMapping("userLoginRm")
    public String userLogin(HttpSession session) {
        session.setAttribute("user", "rememberMe");
        return "main";
    }

    /**
     * 登录认证验证角色
     */
    @RequiresRoles("admin")
    @GetMapping("/userLoginRoles")
    @ResponseBody
    public String userLoginRoles() {
        System.out.println("登录认证验证角色");
        return "验证角色成功";
    }

    /**
     * 登录认证验证权限
     */
    @RequiresPermissions("user:delete")
    @GetMapping("/userLoginPermissions")
    @ResponseBody
    public String userLoginPermissions() {
        System.out.println("验证删除权限");
        return "验证角色删除权限成功";
    }

    /**
     * 登录认证验证权限
     */
    @RequiresPermissions("user:select")
    @GetMapping("/userLoginPermissionsd")
    @ResponseBody
    public String userLoginPermissionsd() {
        System.out.println("验证查询权限");
        return "验证角色查询权限成功";
    }

}
